package com.kuang.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.kuang.common.to.mq.SeckillOrderTo;
import com.kuang.common.utils.R;
import com.kuang.common.vo.MemberRespVo;
import com.kuang.gulimall.seckill.feign.CouponFeignService;
import com.kuang.gulimall.seckill.feign.ProductFeignService;
import com.kuang.gulimall.seckill.intercepter.LoginUserIntercepter;
import com.kuang.gulimall.seckill.service.SeckillService;
import com.kuang.gulimall.seckill.to.SecKillSkuRedisTo;
import com.kuang.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.kuang.gulimall.seckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    //这里是StringRedisTemplate
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:"; //+商品随机码


    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1，扫描需要参与秒杀的活动
        R session = couponFeignService.getLates3DaySession();
        if (session.getCode() == 0) {
            //上架商品
            List<SeckillSessionsWithSkus> sessionData = (List<SeckillSessionsWithSkus>) session.getmyData("data", new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //缓存到redis
            //1，缓存活动信息
            saveSessionInfos(sessionData);
            //2，缓存活动的关联商品信息
            saveSessionSkuInfos(sessionData);

        }
    }

    //返回当前时间可以参与的秒杀商品信息
    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
        //1，确定当前时间属于哪个秒杀场次。
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            //seckill:sessions:1628389660000_1628501260000
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);
            if (time >= start && time <= end) {
                //2，获取当前时间的秒杀场次的所以商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                //类型转换有问题，上面的操作一定要约束泛型
                List<String> list = hashOps.multiGet(range);
                if (list != null) {
                    List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                        SecKillSkuRedisTo redis = JSON.parseObject((String) item, SecKillSkuRedisTo.class);
//                        redis.setRandomCode(null);当前秒杀开始就需要随机码
                        return redis;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }

        return null;

    }

    @Override
    public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {

        //1，找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                //不要在redis里面正则，操作层面的业务最好都在业务层实现
                //简而言之就是不要在数据层执行业务操作
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SecKillSkuRedisTo skuRedisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);

                    //随机码不能给出去
                    long current = new Date().getTime();
                    //找到现在属于秒杀时间内的商品，把不是现在的商品随机码置空，这样就避免数据库被侵入
                    if (current > skuRedisTo.getStartTime() && current < skuRedisTo.getEndTime()) {
                    } else {
                        skuRedisTo.setRandomCode(null);
                    }

                    return skuRedisTo;
                }

            }
        }
        return null;
    }

    /**
     * 秒杀
     *
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {

        MemberRespVo respVo = LoginUserIntercepter.loginUser.get();
        //1，获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = hashOps.get(killId);
        if (StringUtils.isEmpty(s)) {
            return null;
        } else {
            SecKillSkuRedisTo redis = JSON.parseObject(s, SecKillSkuRedisTo.class);
            //校验合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long time = new Date().getTime();

            long ttl = endTime - time;
            //1，校验时间的合法性
            if (time >= startTime && time <= endTime) {
                //校验随机码和商品id
                String randomCode = redis.getRandomCode();
                Long skuId = redis.getSkuId();
                Long promotionSessionId = redis.getPromotionSessionId();
                String Session_skuId = promotionSessionId + "_" + skuId;
                if (randomCode.equals(key) && killId.equals(Session_skuId)) {
                    //3，验证购物数量是否合理（信号量跟现在购物数量的对比）
                    if (num <= redis.getSeckillLimit().intValue()) {
                        //4，验证这个人是否已经购买过。幂等性；如果只要秒杀成功就去占位。userId_SessionId_skuId
                        //SETNX
                        String redisKey = respVo.getId() + "_" + skuId;
                        //自动过期，这里的判断是为了分布式场景下，多业务共同抢占做准备，这样可以避免其他业务先抢占了。
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功说明从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                //秒杀成功
                                //快速下单，发送MQ消息，10ms
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                seckillOrderTo.setOrderSn(timeId);
                                seckillOrderTo.setMemberId(respVo.getId());
                                seckillOrderTo.setNum(num);
                                seckillOrderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                seckillOrderTo.setSkuId(redis.getSkuId());
                                seckillOrderTo.setSeckillPrice(redis.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);
                                return timeId;
                            }
                            return null;


                        } else {
                            //说明已经买过了
                            return null;
                        }
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }
        return null;
    }

    /**
     * 保存活动信息
     *
     * @param sessionData
     */
    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            //Long与Date有什么区别
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            //缓存活动信息，同时通过redis读取锁解决幂等性问题
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }

        });
    }

    /**
     * 保存商品相关信息
     *
     * @param sessionData
     */
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                //4，引入随机码，防止接口被小工具攻击，接口会变成seckill?skuId=1&key=dalsdfdk
                String token = UUID.randomUUID().toString().replace("-", "");

                Boolean skuVo_hasKey = ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString());
                if (!skuVo_hasKey) {

                    //缓存商品
                    SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                    //1，sku的基本数据
                    R r_skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (r_skuInfo.getCode() == 0) {
                        SkuInfoVo skuInfo = (SkuInfoVo) r_skuInfo.getmyData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(skuInfo);
                    }
                    //2，sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);

                    //3，设置上当前商品的秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    redisTo.setRandomCode(token);
                    //转换成json存入redis中
                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString(), jsonString);

                    //如果当前这个场次的商品的库存已经上架就不需要上架
                    //5，信号量，设置分布式信号量提升高并发的能力，减库存也会被随机码保护，作用，限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                }

            });
        });
    }


}
